#!/usr/bin/env python
# coding=utf-8

from QRServer.utility import handle_time_string
import xlrd
from models import*



def handle_update_index(raw):
    info = dict(new_type_num=None, new_device_num=None, error=False)
    try:
        device_dic = dict(
            num=raw[1].encode('utf-8'),
            name=raw[2].encode('utf-8'),
            price=raw[6],
            cost=raw[7],
            man=raw[10].encode('utf-8'),
            location=raw[13].encode('utf-8'),
            status=raw[15].encode('utf-8'),
            unit=raw[9].encode('utf-8'),
            date_of_purchase=handle_time_string(raw[21].encode('utf-8'), "%Y-%m-%d")
        )

        type_dic = dict(
            num=raw[3].encode('utf-8'),
            name=raw[4].encode('utf-8'),
            manufacturer=raw[16].encode('utf-8'),
            pattern=raw[17].encode('utf-8'),
            standard=raw[18].encode('utf-8')
        )
    except:
        info['error'] = True
        return info

    theType, created = Type.objects.get_or_create(
        num=type_dic['num'],
        defaults=dict(
            name=type_dic['name'],
            manufacturer=type_dic['manufacturer'],
            pattern=type_dic['pattern'],
            standard=type_dic['standard'],
        )
    )
    if created:
        info['new_type_num'] = theType.num
    else:
        Type.objects.filter(num=type_dic['num']).update(**type_dic)

    theDevice, created = Device.objects.get_or_create(
        num=device_dic['num'],
        defaults=dict(
            name=device_dic['name'],
            price=device_dic['price'],
            cost=device_dic['cost'],
            man=device_dic['man'],
            location=device_dic['location'],
            status=device_dic['status'],
            unit=device_dic['unit'],
            date_of_purchase=device_dic['date_of_purchase'],
            type=theType
        ))
    if created:
        info['new_device_num'] = theDevice.num
    else:
        Device.objects.filter(num=device_dic['num']).update(**device_dic)
    return info


def xls_update(path):
    try:
        data = xlrd.open_workbook(path)
    except:
        update_error_message = "文件上传失败,或文件类型错误（xls版本只支持2003）"
        return update_error_message, True
    table = data.sheet_by_index(0)
    new_type = []
    new_device = []
    for i in range(1,table.nrows):
        raw = table.row_values(i)
        message = handle_update_index(raw)
        if message['error']:
            update_error_message = "文件类型错误（xls版本只支持2003）"
            return update_error_message, True
        else:
            new_type.append(message['new_type_num'])
            new_device.append(message['new_device_num'])
    return [new_type, new_device], False